package com.ygqh.baby.service.pay.app.alipay;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeRefundApplyModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ygqh.baby.ao.AppType;
import com.ygqh.baby.ao.CodeConstant;
import com.ygqh.baby.ao.PayType;
import com.ygqh.baby.ao.ResponseEntity;
import com.ygqh.baby.service.pay.app.AppPaySuccessHandler;

@Component
public class AlipayAppApi {
	protected final Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	private AppPaySuccessHandler appPaySuccessHandler;

	public AlipayTradeAppPayModel getAlipayTradeAppPayModel(String body, String subject, String paymentCode, String timeOut, String price,
			String passbackParams) {

		// SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setBody(body);
		model.setSubject(StringUtils.isBlank(subject) ? "壹果订单" : subject);
		model.setOutTradeNo(paymentCode);
		model.setTimeoutExpress(StringUtils.isBlank(timeOut) ? "30m" : timeOut);
		model.setTotalAmount(price);
		model.setProductCode("QUICK_MSECURITY_PAY");
		model.setGoodsType("1");
		model.setPassbackParams(passbackParams);
		return model;

	};

	public AlipayTradeAppPayModel getAlipayTradeAppPayModel(String paymentCode, String price, String passbackParams) {
		// SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setBody(null);
		model.setSubject("壹果订单");
		model.setOutTradeNo(paymentCode);
		model.setTimeoutExpress("30m");
		model.setTotalAmount(price);
		model.setProductCode("QUICK_MSECURITY_PAY");
		model.setGoodsType("1");
		model.setPassbackParams(passbackParams);
		return model;

	};

	public String alipayTradeAppPay(String paymentCode, String price, String passbackParams, AppType appType) {
		String orderInfo = null;
		AlipayClient alipayClient = AlipayAppUtils.alipayClient;
		// 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		AlipayTradeAppPayRequest alipayRequest = new AlipayTradeAppPayRequest();

		AlipayTradeAppPayModel model = this.getAlipayTradeAppPayModel(paymentCode, price, passbackParams);
		alipayRequest.setBizModel(model);
		alipayRequest.setNotifyUrl(AlipayAppUtils.payNotifyUrl);
		// 这里和普通的接口调用不同，使用的是sdkExecute
		try {
			AlipayTradeAppPayResponse response = alipayClient.sdkExecute(alipayRequest);
			orderInfo = response.getBody();
			System.out.println(response.getBody());// 就是orderString
													// 可以直接给客户端请求，无需再做处理。
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}

		return orderInfo;
	}

	public ResponseEntity alipayTradeRefund(AppType appType, String paymentCode, String returnCode, BigDecimal refundAmount, String refundReason,
			String handler) {

		AlipayClient alipayClient = AlipayAppUtils.alipayClient;
		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

		AlipayTradeRefundApplyModel mode = new AlipayTradeRefundApplyModel();

		mode.setOutTradeNo(paymentCode);
		mode.setRefundAmount(refundAmount.toString());
		mode.setRefundReason(refundReason);
		mode.setOutRequestNo(returnCode);
		mode.setOperatorId(handler);

		request.setBizModel(mode);

		try {
			AlipayTradeRefundResponse response = alipayClient.execute(request);

			String responseMsg = AlipayAppUtils.getResponseMsg(response);
			if (response.isSuccess()) {
				return new ResponseEntity(CodeConstant.Success.getCode(), CodeConstant.Success.getTitle(), responseMsg);
			} else {
				return new ResponseEntity(CodeConstant.ThirdApiError.getCode(), CodeConstant.ThirdApiError.getTitle(), responseMsg);
			}
		} catch (AlipayApiException e) {
			String errorMsg = "支付宝退款失败；appType=" + appType + ";returnCode=" + returnCode + ";paymentCode=" + paymentCode + ";refundAmount=" + refundAmount
					+ ";handler=" + handler;
			logger.error(errorMsg);
			e.printStackTrace();
			return new ResponseEntity(CodeConstant.Error.getCode(), CodeConstant.Error.getTitle(), errorMsg);
		}
	}

	public String alipayCallBack(Map<String, String[]> parameterMap) {
		String result = new AppAlipayNotifyTemplate(parameterMap).execute(new PaySuccessCallBack() {

			@Override
			public void onSuccess(String tradeNo, String paymentCode, AppType appType, JSONObject passbackParams, String tradeStatus, BigDecimal paidPrice,
					Date paidTime) {
				appPaySuccessHandler.paySuccess(PayType.Alipay, paymentCode, tradeNo, paidPrice, paidTime, passbackParams);

			}
		});

		return result;

	}

}
